const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const glob = require('glob');
const app = express();
const log = require('./utils/logger')
const { port } = require('./config')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.all('*', function (req, res, next) {
  log.info(`访问接口:${req.url}`);
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With, xtoken");
  res.header("Access-Control-Allow-Methods", "PUT, GET, OPTIONS, POST, DELETE");
  res.header("X-Powered-By", "ngsoftware-core");
  res.header("Content-Type", "application/json;charset=utf-8");
  next();
});

glob('./router/**/*', {}, (err, files) => {
  if (err) {
    throw err;
  }
  files.forEach(item => {
    const router = require(item);
    if (router instanceof Function) {
      app.use(router);
    }
  });
  app.use((err, req, res, next) => {
    res.state(200).send({
      code: 500,
      msg: err,
      data: 'Error'
    });
  });
});

app.disable('etag');

app.listen(port, () => {
  log.success(`Server listening on ${port}`);
});
